package com.example.fuluchou.controller;

import com.example.fuluchou.common.pojo.CommonResult;
import com.example.fuluchou.common.untils.JacksonUtil;
import com.example.fuluchou.controller.param.DrawPrizeParam;
import com.example.fuluchou.controller.param.ShowWinningRecordsParam;
import com.example.fuluchou.controller.result.WinningRecordResult;
import com.example.fuluchou.service.DrawPrizeService;
import com.example.fuluchou.service.dto.WinnerRecordDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DrawPrizeController {

    private static final Logger logger = LoggerFactory.getLogger(DrawPrizeController.class);

    @Autowired
    DrawPrizeService drawPrizeService;

    /**
     *  步抽奖，接⼝只做奖品数校验即可返回。
     * @param param
     * @return
     */
    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(
           @Validated @RequestBody DrawPrizeParam param) {
        logger.info("drawPrize DrawPrizeParam: "+JacksonUtil.writeValueAsString(param));
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordResult>> showWinningRecords(
            @Validated @RequestBody ShowWinningRecordsParam param) {
        logger.info("showWinningRecords ShowWinningRecordsParam:{}",
                JacksonUtil.writeValueAsString(param));
        List<WinnerRecordDTO> winnerRecordDTOList = drawPrizeService.getRecords(param);
        return CommonResult.success(converToWinningRecordResultList(winnerRecordDTOList));

    }

    private List<WinningRecordResult> converToWinningRecordResultList(
            List<WinnerRecordDTO> winnerRecordDTOList) {
        if(CollectionUtils.isEmpty(winnerRecordDTOList)){
            return Arrays.asList();
        }
        return winnerRecordDTOList.stream()
                .map(winnerRecordDTO -> {
                    WinningRecordResult result = new WinningRecordResult();
                    result.setWinnerId(winnerRecordDTO.getWinnerId());
                    result.setWinnerName(winnerRecordDTO.getWinnerName());
                    result.setPrizeName(winnerRecordDTO.getPrizeName());
                    result.setPrizeTier(winnerRecordDTO.getPrizeTier().getMessage());
                    result.setWinningTime(winnerRecordDTO.getWinningTime());
                    return result;
                })
                .collect(Collectors.toList());

    }
}
